package tech.ideashare.conf;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

public class MybatisConfig {

    private SqlSessionFactory sessionFactory;

    public  void initConfig(){
        if (!sessionFactory.getConfiguration().isResourceLoaded("mybatis-conf.xml")){
            String resource = "mybatis-conf.xml";
            InputStream inputStream = null;
            try {
                inputStream = Resources.getResourceAsStream(resource);
            } catch (IOException e) {
                e.printStackTrace();
            }
            SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
            this.sessionFactory = sqlSessionFactory;
        }

//        SqlSession sqlSession = sqlSessionFactory.openSession();
//        PostDao mapper = sqlSession.getMapper(PostDao.class);
//        List<PostArticle> articles = mapper.findAll();
//        System.out.println(articles);
    }


    public <T> T getMapper(SqlSession sqlSession, Class<T> clazz){
        T t = sqlSession.getMapper(clazz);
        return  t;
    }


    public SqlSession getSession(){
        return sessionFactory.openSession();
    }





}
